<?php


namespace app\admin\model;
use Gregwar\Captcha\CaptchaBuilder;
use think\facade\Session;

class Captcha
{
    //登录验证码 key
    const LOGIN_CAPTCHA = 'login-captcha';

    /**
     * 获取验证码图片
     */
    public function getLoginCaptcha(){
        $builder = new CaptchaBuilder(4);
        $builder->build(100,38);
        $phrase = strtolower($builder->getPhrase());
        Session::set(self::LOGIN_CAPTCHA,$phrase);
        return $builder->get(100);
    }

    /**
     * 校验验证码
     * @param string $key Session key
     * @param string $val code 待检验验证码
     * @param bool $clear  是否清除
     * @return bool
     */
    public function checkCaptcha($key,$val,$clear=true){
        $pCheck = '/^[a-zA-Z0-9]{4}$/';
        if (!preg_match($pCheck, $val)) return false;
        $check = Session::get($key) === $val;
        $clear && Session::delete($key);
        return $check;
    }

}